<?php
namespace Api
{

    class   Mail extends \Api\View
    {
    
        // Server e-mail address
        const SERVER_MAIL = 'local';
    
        public function __construct(array $config=array())
        {                        
            parent::__construct($config, \Api\Config::$param);    
        }
        
        final public function display($template = null)
        {
            if(!$template) return null;		
			
			$template = 'mail/'.$template.'.tpl';
			$module = \Api\Config::$param[\Api\ObjectLoader::C_MODULE];
            
			if(strlen($template) == 0 || !is_file(BASE_PATH.'/'.$module.'/view/'.$template))
				throw new \Exception('MAIL: Template file dosn\t exists '.$template);
			
           return $this->m_smarty->fetch($template);
        }
        
        /**
         *  Send current template to address
         *  @param sender address
         *  @param recipient
         *  @param message
         *  @param topic
         *  @param template
         *  @param special smarty variable
         *  @return bool
         */
        public function Send($from, $address, $message, $topic, $template,
            array $special = array())
        {
            if($from == null)
            {
                $from = self::SERVER_MAIL;
            }
            $this->address = strip_tags($address);            
            $this->message = strip_tags($message);           
            
            foreach($special as $k => $v)
            {
                $this->$k = strip_tags($v);
            }
            
            $headers = "MIME-Version: 1.0"."\r\n";            
            $headers.= "Content-type:text/html;charset=utf-8"."\r\n";
 		    $headers.= "From: ".strip_tags($from)."\r\n";
 		    $headers.= "Reply-To: ".strip_tags($address)."\r\n";
            
            $message = $this->display($template);
            
            return mail($address, $topic, $message, $headers); 	
        }
        
        const _TOKEN_ = 'mail_token'; // identyfikator tokena
        
        /**
         * Generuje token dla e-maila. Zwraca jego wartość
         * @return string
         * @static         
         */
        static public function GenerateToken()
        {
            $token = md5(rand().rand().rand());            
            \Api\Session::set(self::_TOKEN_, $token);
            
            return $token;
        }
        
        /**
         * Sprawdza czy podany token jest zgodny z tokenem
         * zawartym argumencie
         * @param wartość tokena otrzymana od użytkownika
         * @return bool
         */
        static public function CompareToken($token)
        {
            return (\Api\Session::get(self::_TOKEN_) == $token);
        }
    }
}
?>